<script setup>
import {ref} from "vue";
import utils from '@/utils/storage'
import CodeMirror from "@/components/codeMirror.vue";
import "vue3-video-play/dist/style.css";
import {videoPlay as Vue3VideoPlay} from "vue3-video-play";
import local from "@/axios/local"; // 改个别名
const fileItem = ref(null)
const visible = ref(false)

async function show(data) {
  fileItem.value = JSON.parse(JSON.stringify(data))
  visible.value = true
  let res = await local.get(`/cloud/downloadQiNiuUrl?key=${data.path}`)
  fileItem.value.path = res.data
  if (utils.returnFileType('图片', data.path)) {
    fileItem.value.path = 'http://www.forgetting.ren/' + data.path
  }

  if (utils.returnFileType('文本', data.path)) {
    local.get(fileItem.value.path, {
      headers: {
        "Content-Type": "application/json; charset=UTF-8"
      },
      responseType: 'arraybuffer',
    }).then(r => {
      const d = new TextDecoder('utf-8')
      fileItem.value.data = d.decode(new Uint8Array(r))
    })
  }
}

defineExpose({
  show
})
</script>

<template>
  <div>
    <el-dialog draggable v-model="visible" width="80%" :close-on-press-escape="false" title="文件预览">
      <div v-if="fileItem" class="preview">
        <div v-if="utils.returnFileType('图片',fileItem.name)" class="file">
          <img :src="fileItem.path" alt="">
        </div>
        <div v-else-if="utils.returnFileType('视频',fileItem.name)" class="file">
          <Vue3VideoPlay width='100%' height="100%" :speed="false" color="#5486AB"
                         :controlBtns="['speedRate', 'volume', 'pageFullScreen', 'fullScreen']" :src="fileItem.path"/>

        </div>
        <div v-else-if="utils.returnFileType('音频',fileItem.name)" class="file">
          <audio :src="fileItem.path"></audio>
        </div>
        <div v-else-if="utils.returnFileType('文档',fileItem.name)" class="file">
          <iframe :src="fileItem.path"></iframe>
        </div>
        <div v-else-if="utils.returnFileType('压缩包',fileItem.name)" class="file">
          <span>不支持预览压缩包</span>
        </div>
        <div v-else-if="utils.returnFileType('文本',fileItem.name)" class="file">
          <code-mirror :data="fileItem.data"></code-mirror>
        </div>
        <div v-else class="file">
          <span>不支持预览</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.preview {
   height: 60vh;
  overflow-y: hidden;
  .file {
     height: 100%;
  }

  img, video {
    max-width: 100%;
    height: auto;
  }
}
</style>
